package auctions;

import jade.core.Agent;

import jade.domain.FIPAAgentManagement.RefuseException;

import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import jade.proto.AchieveREResponder;


public class EnglishBuyer extends AchieveREResponder {

    private transient EnglishBuyerStrategy strategy;
    
    private int maxPrice;
    
    private int myPrice;
    
    private boolean done;
    
    static final String ACL_USERDEF_TERMINATED_SESSION = 
        "iterated-fipa-request-terminated-session";

    public EnglishBuyer(Agent agent, MessageTemplate mt, 
                        EnglishBuyerStrategy strategy, int maxPrice) {
        super(agent, mt);
        this.strategy = strategy;
        this.maxPrice = maxPrice;
        myPrice = 0;
        done = false;
    }

    protected ACLMessage handleRequest(ACLMessage request) 
    throws RefuseException {
        if(done) {
            myAgent.doDelete();
        }
        ((BuyerAgent)myAgent).sendBuyerInfo(request.getSender(), maxPrice, 1);
        ACLMessage reply = request.createReply();
        int price = Integer.parseInt(request.getContent());
        reply.setPerformative(ACLMessage.AGREE);
        if(request.getPerformative() == ACLMessage.ACCEPT_PROPOSAL) {
            maxPrice -= price;
            ((BuyerAgent)myAgent).sendBuyerInfo(request.getSender(), maxPrice, 
                                                0);
            done = true;
            return reply;
        } else {
            myPrice = strategy.acceptOffer(1, 1, price, maxPrice);
            if(myPrice > 0) {
                return reply;  
            } else {
                throw new RefuseException("");
            }
        }
    }
    
    protected ACLMessage prepareResultNotification(ACLMessage request,
                                                   ACLMessage response) {
        ACLMessage reply = request.createReply();
        reply.setContent(myPrice + "");
        reply.setPerformative(ACLMessage.INFORM);
        if(done) {
            closeSessionOnNextReply(reply);
        }
        return reply;
    }

    private void closeSessionOnNextReply(ACLMessage reply) {
        reply.addUserDefinedParameter(ACL_USERDEF_TERMINATED_SESSION, "true");
    }
}
